<template>
    <div>
        <el-row :gutter="20">
           <el-col :span="6">
                <el-input placeholder="请输入用户名" v-model="username" ></el-input>
           </el-col>
            <el-col :span="5">
                <el-select  v-model="State" clearable  placeholder="请选择角色">
                    <el-option
                            label="供应商"
                            value="1"
                    >
                    </el-option>
                    <el-option
                            label="商户"
                            value="2"
                    >
                    </el-option>
                </el-select>
            </el-col>
            <el-col :span="7">
                <el-button  type="primary" icon="el-icon-search" @click="querybyuname">查询</el-button>
            </el-col>
            <el-col :span="3">
                <el-button type="primary" icon="el-icon-edit" circle @click="add">添加用户</el-button>
            </el-col>
        </el-row>
        <br> <br>
        <el-table
                :data="users"
                style="width: 100%">
            <el-table-column
                    label="账号"
                    width="180">
                <template slot-scope="scope">
                    <i class="el-icon-edit"></i>
                    <span style="margin-left: 10px">{{scope.row.account}}</span>
                </template>
            </el-table-column>
            <el-table-column
                    label="用户名"
                    width="180">
                <template slot-scope="scope" >
                    <el-popover trigger="hover" placement="top">
                        <p>用户名: {{scope.row.uname}}</p>
                        <p>密码: {{scope.row.upwd}}</p>
                        <p>状态:<span v-if="scope.row.accountState==0">未冻结</span>
                            <span v-else>已冻结</span>
                        </p>
                        <div slot="reference" class="name-wrapper">
                            <el-tag size="medium">{{scope.row.uname}}</el-tag>
                        </div>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column
                    label="手机号"
                    width="180">
                <template slot-scope="scope">
                    <i class="el-icon-s-tools"></i>
                    <span style="margin-left: 10px" v-if="scope.row.phone==null || scope.row.phone==''">未绑定</span>
                    <span style="margin-left: 10px" v-else >{{scope.row.phone}}</span>
                </template>
            </el-table-column>
            <el-table-column
                    label="邮箱"
                    width="190">
                <template slot-scope="scope">
                    <i class="el-icon-s-tools"></i>
                    <span style="margin-left: 10px" v-if="scope.row.mailAddress==null || scope.row.mailAddress==''">未绑定</span>
                    <span style="margin-left: 10px" v-else >{{scope.row.mailAddress}}</span>
                </template>
            </el-table-column>
            <el-table-column
                    label="头像"
                    width="180">
                <template slot-scope="scope">
                    <div >
                        <el-avatar :src="'http://127.0.0.1:9090/demo/'+scope.row.usersTopImg"></el-avatar>
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                    label="状态"
                    width="100">
                <template slot-scope="scope">
                    <i v-if="scope.row.accountState==0" class="el-icon-success"></i>
                    <i v-else class="el-icon-error"></i>
                    <span style="margin-left: 10px" v-if="scope.row.accountState==0">未冻结</span>
                    <span style="margin-left: 10px" v-else>冻结</span>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-dropdown split-button type="primary" @click="handleClick">
                        功能
                        <el-dropdown-menu slot="dropdown">

                            <el-button v-if="scope.row.mailAddress!=null && scope.row.mailAddress!=''"
                                    size="mini"
                                    icon="el-icon-message"
                                    type="warning"
                                    plain
                                    @click="editMail(scope.row.id)">重置邮箱
                            </el-button>
                            <el-button v-else
                                       icon="el-icon-message"
                                       size="mini"
                                       plain
                                       >未绑邮箱
                            </el-button>
                            <br>
                            <br>
                            <el-button v-if="scope.row.phone!=null && scope.row.phone!=''"
                                       size="mini"
                                       type="warning"
                                       icon="el-icon-edit"
                                       plain
                                       @click="phonebinding(scope.row.id)">重置手机
                            </el-button>
                            <el-button v-else
                                       size="mini"

                                       icon="el-icon-edit"
                                       plain
                            >未绑手机
                            </el-button>

                            <br>
                            <br>
                            <el-button
                                    size="mini"
                                    type="warning"
                                    plain
                                    icon="el-icon-edit"
                                    @click="edit(scope.row.id)">编辑用户
                            </el-button>

                            <br>
                            <br>
                            <el-popconfirm v-if="scope.row.accountState==0"
                                           confirm-button-text='确定'
                                           cancel-button-text='取消'
                                           icon="el-icon-info"
                                           icon-color="red"
                                           title="你确定冻结吗？"
                                           @confirm="alterSystembyid(scope.row.id)"
                            >
                                <el-button
                                        plain
                                        slot="reference"
                                        size="mini"
                                        type="danger"
                                        icon="el-icon-error">冻结用户</el-button>
                            </el-popconfirm>


                            <el-popconfirm v-else
                                           title="你确定解冻吗？"
                                           @confirm="alterSystembyid(scope.row.id)"
                            >
                                <el-button
                                        plain
                                        slot="reference"
                                        size="mini"
                                        type="success"
                                        icon="el-icon-success"
                                >解冻用户</el-button>
                            </el-popconfirm>
                            <br>
                            <br>
                            <el-button
                                    size="mini"
                                    type="primary"
                                    icon="el-icon-edit"
                                    plain
                                    @click="drawerbyOpen(scope)">修改密码</el-button>
                        </el-dropdown-menu>
                    </el-dropdown>

                </template>
            </el-table-column>
        </el-table>

        <template>
            <div class="block">
                <span class="demonstration"></span>
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="pageno"
                        :page-sizes="[5, 10, 15, 20]"
                        :page-size="pagesize"
                        layout="total, sizes, prev, pager   , next, jumper"
                        :total="total">
                </el-pagination>
            </div>
        </template>

        <el-dialog
                title="添加用户"
                :visible.sync="dialogVisible"
                width="35%"
                :before-close="handleClose">
            <component ref="staffadd" :is="cont"></component>
            <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">关 闭</el-button>
  </span>
        </el-dialog>


        <el-dialog
                title="编辑"
                :visible.sync="dialogVisible"
                width="40%"
                :before-close="handleClose">
            <component ref="eideusers" :is="cont"></component>
            <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">关 闭</el-button>
  </span>
        </el-dialog>


        <!-- 修改密码的模态框 -->
        <el-form  :model="ruleForm" status-icon  label-width="100px" class="demo-ruleForm">

            <el-drawer
                    title="请输入你原来的密码"
                    :visible.sync="drawer"
                    :before-close="handleClose03"
                    size="50%">
                <div>
<!--                    <el-form-item  label="原来的密码" >-->
<!--                        <el-input  type="password" v-model="ruleForm.suPwd" autocomplete="off"></el-input>-->
<!--                    </el-form-item>-->
                    <el-form-item label="新的密码" >
                        <el-input  type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="请再次输入新的密码" >
                        <el-input  type="password" v-model="ruleForm.uppwd" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-button @click="submitForm()">提交</el-button>
<!--                    <el-button @click="nenx">下一步</el-button>-->
                    <el-drawer
                            title="新的密码"
                            :append-to-body="true"
                            :before-close="handleClose02"
                            :visible.sync="innerDrawer">

                    </el-drawer>
                </div>
            </el-drawer>

        </el-form>

        <!-- 修改邮箱的模态框 -->
        <el-form  :model="ruleForm" status-icon  label-width="100px" class="demo-ruleForm">

            <el-drawer
                    title="新的的邮箱"
                    :visible.sync="miledrawer"
                    :before-close="handleClose03"
                    size="50%">
                <div>
                    <el-form-item  label="新的的邮箱" >
                        <el-input  type="text" v-model="ruleForm.mail" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-button @click="submitmile()">提交</el-button>
                    <!--                    <div>-->
<!--                        <el-form-item  label="验证码" >-->
<!--                            <el-row>-->
<!--                                <el-col :span="6">-->
<!--                                    <el-input class="el-col-md-5" type="text" v-model="validation" autocomplete="off"></el-input>-->
<!--                                </el-col>-->
<!--                                <el-col :span="3">-->
<!--                                    <el-link @click="createdCode('mile')">获取验证码</el-link>-->
<!--                                </el-col>-->
<!--                                <el-col :span="5">-->
<!--                                    <div class="s-canvas" @click="createdCode('mile')">-->
<!--                                        <canvas  id="mile"  :width="contentWidth" :height="contentHeight"></canvas>-->
<!--                                    </div>-->
<!--                                </el-col>-->
<!--                                <br><br>-->
<!--                                <el-button @click="submitmile()">提交</el-button>-->
<!--                            </el-row>-->
<!--                        </el-form-item>-->
<!--                    </div>-->
                </div>
            </el-drawer>

        </el-form>

        <!-- 绑定手机的模态框 -->
        <el-form  :model="ruleForm" status-icon  label-width="100px" class="demo-ruleForm">

            <el-drawer
                    title="请输入手机号"
                    :visible.sync="phonedrawer"
                    :before-close="handleClose03"
                    size="50%">
                    <el-form-item   label="手机号" >
                        <el-input  type="text" v-model="ruleForm.phone" autocomplete="off"></el-input>
                    </el-form-item>
<!--                <div>-->
<!--                    <el-form-item  label="验证码" >-->
<!--                        <el-row>-->
<!--                            <el-col :span="7">-->
<!--                                <el-input class="el-col-md-5" type="text" v-model="validation" autocomplete="off"></el-input>-->
<!--                            </el-col>-->
<!--                            <el-col :span="3">-->
<!--                                <el-link @click="createdCode('s-canvas')">获取验证码</el-link>-->
<!--                            </el-col>-->
<!--                            <el-col :span="5">-->
<!--                                <div class="s-canvas" @click="createdCode('s-canvas')">-->
<!--                                    <canvas  id="s-canvas"  :width="contentWidth" :height="contentHeight"></canvas>-->
<!--                                </div>-->
<!--                            </el-col>-->
<!--                            <br><br>-->
<!--                            <el-button @click="submitphone()">提交</el-button>-->
<!--                        </el-row>-->
<!--                    </el-form-item>-->
<!--                </div>-->
                <el-button @click="submitphone()">提交</el-button>
            </el-drawer>

        </el-form>

    </div>

</template>

<script>

    import AddUser from "./AddUser";
    import Vue from 'vue'
    import EideUsers from "./EideUsers";

    let eli = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/
    let pwd02= /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/
    let phone = /^1[3|4|5|7|8][0-9]{9}$/

    export default Vue.extend({
        props: {
            fontSizeMin: {
                type: Number,
                default: 25
            },
            fontSizeMax: {
                type: Number,
                default: 30
            },
            backgroundColorMin: {
                type: Number,
                default: 255
            },
            backgroundColorMax: {
                type: Number,
                default: 255
            },
            colorMin: {
                type: Number,
                default: 0
            },
            colorMax: {
                type: Number,
                default: 160
            },
            lineColorMin: {
                type: Number,
                default: 100
            },
            lineColorMax: {
                type: Number,
                default: 255
            },
            dotColorMin: {
                type: Number,
                default: 0
            },
            dotColorMax: {
                type: Number,
                default: 255
            },
            contentWidth: {
                type: Number,
                default: 120
            },
            contentHeight: {
                type: Number,
                default: 34
            }
        },
        data() {
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (this.ruleForm.checkPass !== '') {
                        this.$refs.ruleForm.validateField('checkPass');
                    }
                    callback();
                }
            };
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入新的密码'));
                } else {
                    if (this.ruleForm.checkPass !== '') {
                        this.$refs.ruleForm.validateField('checkPass');
                    }
                    callback();
                }
            };
            var validatePass3 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.ruleForm.uppwd) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return {
                validation:"",//验证
                identifyCode: '',//获取随机数的
                ruleForm: {
                    checkPass:"",
                    uppwd:"",
                    suPwd:"",
                    mail:"",
                    upmail:"",
                    phone:""
                },
                pwd:"",//存放临时的手机号
                mai:"",//存放临时的邮箱信息
                uid:"",//存放用户id
                miledrawer:false,
                phonedrawer:false,
                drawer: false,
                innerDrawer: false,
                mailinnerDrawer:false,
                url:'http://127.0.0.1:9090/demo/',
                users:[],//用来存后端传来的数据
                username:"",//查询条件
                State:"",//查询条件
                pageno:1,   //页码
                pagesize:5,   //页size
                total:1,   //查询到的总记录数量
                cont:"",
                dialogVisible: false,

            }
        },
        mounted() {
            //this.createdCode();
        },
        conponents:{
            AddUser,
            EideUsers
        },
        methods: {
            //获取员工数据
            getdata(){
                var params = new URLSearchParams();
                params.append("pageno",this.pageno);
                params.append("pagesize",this.pagesize);
                params.append("uName",this.username)
                if (this.State == 1){
                    params.append("commercialState",1);
                }
                if (this.State == 2){
                    params.append("supplierState",1);
                }
                this.$axios.get("users.action",{params:params}).
                then(response=>{
                    console.log(response.data.records)
                    this.users = response.data.records
                    this.total = response.data.total;
                }).
                catch()
            },
            //修改状态
            alterSystembyid(uid){
                let id = new URLSearchParams();

                id.append("id",uid)

                this.$axios.post("eideUserbyaccountState.action",id).
                then(request=>{
                    if (request.data.msg=="成功"){
                        this.getdata()
                        this.$message.success("成功")
                    }else {
                        this.$message.error("失败")
                    }
                }).
                catch()


            },
            handleEdit(index, row) {
                //console.log(index, row);
            },
            //添加
            add(){
                this.cont = AddUser;
                this.dialogVisible = true;
                //this.$refs.staffadd.submitForm();
            },
            //修改用户
            edit(id){
                this.cont = EideUsers;
                this.dialogVisible = true;
                this.$nextTick(item=>{
                    this.$refs.eideusers.getdata(id);
                })

            },
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {});
            },

            //---------分页查询----------//

            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pagesize = val;
                this.getdata()
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.pageno = val;
                this.getdata()
            },
            querybyuname(){
                this.username = this.username
                this.getdata()
            },

            //-----修改密码-----//

            handleClose02(done) {
                this.$confirm('确定关闭吗')
                    .then(_ => {
                        done();
                        this.ruleForm.mail = ""
                        this.mail = ""
                        this.ruleForm.checkPass = ""
                        this.ruleForm.uppwd = ""
                    })
                    .catch(_ => {});
            },
            handleClose03(done) {
                        done()
                        this.ruleForm.suPwd = ""
                        this.ruleForm.upmail = ""
                        this.ruleForm.phone = ""
                        this.validation = ""
                        this.mail=""

            },

            drawerbyOpen(user){
                this.uid = user.row.id
                this.pwd = user.row.upwd
                this.drawer = true
            },
            // nenx(){
            //     if (this.ruleForm.suPwd == this.pwd){
            //         this.innerDrawer = true
            //
            //     }else{
            //         this.$message.warning("密码输入错误");
            //     }
            // },
            submitForm() {
                let syUser = new URLSearchParams();
                if (pwd02.test(this.ruleForm.checkPass)) {
                    if (this.ruleForm.checkPass == this.ruleForm.uppwd) {
                        syUser.append("uPwd",this.ruleForm.checkPass)
                        syUser.append("id",this.uid)
                        this.$axios.post("editUsersbyPwd.action",syUser).
                        then(request=>{
                            if (request.data.msg == "修改成功"){
                                this.$message.success("修改成功")
                                this.getdata();
                                this.ruleForm.checkPass = ""
                                this.ruleForm.uppwd = ""
                                this.ruleForm.suPwd = ""
                                this.innerDrawer = false
                                this.drawer = false
                                this.handleClose03();
                            }else{
                                this.$message.error("修改失败")
                            }
                        }).catch()
                    } else {
                        this.$message.error("两次密码不一致！！")
                    }
                }else {
                    this.$message.warning("密码必须大于或等于8位数且包含至少一个字符！！")
                }
            },
            handleClick() {

            },
            //改绑邮箱
            editMail(mail){
                this.miledrawer = true;
                this.mai = mail;
            },
            //----绑定手机----//
            //打开手机验证的模态框
            phonebinding(id){
                this.phonedrawer = true
                this.uid = id
                this.$nextTick(item=>{
                    this.createdCode(nc)
                })


            },
            submitphone(){
                let users = new URLSearchParams()

                users.append("phone",this.ruleForm.phone)

                this.$axios.post("queryRepetition02.action",users).
                then(request=>{
                    console.log(request.data.msg)
                    if (request.data.msg=='找到了'){
                        this.$message.warning("该手机号已被绑定")
                    }else {
                        if (phone.test(this.ruleForm.phone)){
                            // if (this.identifyCode == this.validation){
                                let users1 = new URLSearchParams()

                                users1.append("phone",this.ruleForm.phone)
                                users1.append("id",this.uid)

                                this.$axios.post("userphonebinding.action",users1).
                                then(item=>{
                                    if (item.data.msg="添加成功"){
                                        this.$message.success("绑定成功")
                                        this.getdata()
                                        this.phonedrawer = false
                                        this.handleClose03();
                                    }else {
                                        this.$message.success("绑定失败")
                                    }
                                }).
                                catch()
                            // }else {
                            //     this.$message.error("验证码输入有误!!")
                            // }
                        }else {
                            this.$message.error("手机号输入有误")
                        }
                    }
                }).
                catch()
            },


            //----绑定邮箱----//
            // milebd(scod){
            //
            // },
            submitmile(){
                let users= new URLSearchParams();
                users.append("id",this.mai);
                users.append("mailAddress",this.ruleForm.mail);
                if (this.ruleForm.mail!=null && this.ruleForm.mail!=""){
                    if (eli.test(this.ruleForm.mail)){
                        this.$axios.post("userphonebinding.action",users).
                        then(request=>{
                            if (request.data.msg=="添加成功"){
                                this.$message.success("重置成功")
                                this.miledrawer=false;
                                this.getdata();
                                this.handleClose03()
                            }else {
                                this.$message.error("重置失败")
                            }
                        }).catch()
                    }else {
                        this.$message.error("邮箱格式错误！")
                    }
                }else {
                    this.$message.error("不能为空")
                }

            },
            //-------验证码--------//

            // 生成4个随机数
            createdCode(id) {
                const len = 4
                const codeList = []
                const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz0123456789'
                const charsLen = chars.length
                for (let i = 0; i < len; i++) {
                    codeList.push(chars.charAt(Math.floor(Math.random() * charsLen)))
                }
                this.identifyCode = codeList.join('')
                this.$emit('getIdentifyCode', this.identifyCode.toLowerCase())
                this.drawPic(id)
            },

            // 生成一个随机数
            randomNum(min, max) {
                return Math.floor(Math.random() * (max - min) + min)
            },
            // 生成一个随机的颜色
            randomColor(min, max) {
                const r = this.randomNum(min, max)
                const g = this.randomNum(min, max)
                const b = this.randomNum(min, max)
                return 'rgb(' + r + ',' + g + ',' + b + ')'
            },

            drawPic(id) {
                const canvas = document.getElementById(id)
                console.log(canvas)
                const ctx = canvas.getContext('2d')
                ctx.textBaseline = 'bottom'
                // 绘制背景
                ctx.fillStyle = this.randomColor(this.backgroundColorMin, this.backgroundColorMax)
                ctx.fillRect(0, 0, this.contentWidth, this.contentHeight)
                // 绘制文字
                for (let i = 0; i < this.identifyCode.length; i++) {
                    this.drawText(ctx, this.identifyCode[i], i)
                }
                this.drawLine(ctx)
                this.drawDot(ctx)
            },

            drawText(ctx, txt, i) {
                ctx.fillStyle = this.randomColor(this.colorMin, this.colorMax)
                ctx.font = this.randomNum(this.fontSizeMin, this.fontSizeMax) + 'px SimHei'
                const x = (i + 1) * (this.contentWidth / (this.identifyCode.length + 1))
                const y = this.randomNum(this.fontSizeMax, this.contentHeight - 5)
                var deg = this.randomNum(-45, 45)
                // 修改坐标原点和旋转角度
                ctx.translate(x, y)
                ctx.rotate(deg * Math.PI / 180)
                ctx.fillText(txt, 0, 0)
                // 恢复坐标原点和旋转角度
                ctx.rotate(-deg * Math.PI / 180)
                ctx.translate(-x, -y)
            },

            // 绘制干扰线
            drawLine(ctx) {
                for (let i = 0; i < 5; i++) {
                    ctx.strokeStyle = this.randomColor(this.lineColorMin, this.lineColorMax)
                    ctx.beginPath()
                    ctx.moveTo(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight))
                    ctx.lineTo(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight))
                    ctx.stroke()
                }
            },

            // 绘制干扰点
            drawDot(ctx) {
                for (let i = 0; i < 80; i++) {
                    ctx.fillStyle = this.randomColor(0, 255)
                    ctx.beginPath()
                    ctx.arc(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight), 1, 0, 2 * Math.PI)
                    ctx.fill()
                }
            },
        },
        created() {
            this.getdata()
        }
    })
</script>

<style scoped>
    .el-dropdown {
        vertical-align: top;
    }
    .el-dropdown + .el-dropdown {
        margin-left: 15px;
    }
    .el-icon-arrow-down {
        font-size: 12px;
    }
</style>